package cc.aliza.lib.mongo.core;

import cc.aliza.lib.mongo.core.annotations.Id;
import cc.aliza.lib.mongo.core.annotations.Reduce;
import cc.aliza.lib.mongo.core.utils.StringUtil;
import org.bson.types.ObjectId;

import java.util.Date;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public abstract class SimpleEntity implements AlizaEntity, Cloneable {

    @Id
    @Reduce
    protected String id;

    @Reduce
    protected Date createTime;

    @Reduce
    protected Date updateTime;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public Date getCreateTime() {
        return createTime;
    }

    @Override
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public Date getUpdateTime() {
        return updateTime;
    }

    @Override
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public long getTimestamp() {
        if (StringUtil.isEmpty(id)) {
            return -1;
        }
        return new ObjectId(id).getTimestamp() * 1000L;
    }


    @Override
    public int hashCode() {
        if (StringUtil.isEmpty(id)) {
            return -1;
        }
        return new ObjectId(id).hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof SimpleEntity)) {
            return false;
        }
        SimpleEntity o = (SimpleEntity) other;
        String oid = o.getId();
        return !(StringUtil.isEmpty(id) || StringUtil.isEmpty(oid)) && id.equalsIgnoreCase(oid);
    }

    @Override
    public String toString() {
        return id;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        SimpleEntity clone;
        try {
            clone = (SimpleEntity) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e); // won't happen
        }

        return clone;
    }

}
